'use client'
import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
// 因 @/components/ui/label 模块不存在，使用原生 label 替代
const Label: React.FC<React.LabelHTMLAttributes<HTMLLabelElement>> = ({ children, ...props }) => (
  <label {...props} className={`block text-sm font-medium text-gray-700 ${props.className || ''}`}>
    {children}
  </label>
);
// 因 @/components/ui/tabs 模块不存在，使用原生标签页实现
const Tabs: React.FC<{ defaultValue: string; className?: string; children: React.ReactNode }> = ({ defaultValue, className, children }) => {
  const [activeTab, setActiveTab] = useState(defaultValue);
  return (
    <div className={className}>
      {React.Children.map(children, (child) =>
        React.isValidElement(child)
          ? React.cloneElement(child, { activeTab, setActiveTab } as any)
          : child
      )}
    </div>
  );
};

const TabsList: React.FC<{ className?: string; children: React.ReactNode; activeTab?: string; setActiveTab?: (v: string) => void }> = ({ className, children, activeTab, setActiveTab }) => {
  return (
    <div className={`flex border-b border-gray-200 ${className || ''}`}>
      {React.Children.map(children, (child) =>
        React.isValidElement(child)
          ? React.cloneElement(child, { activeTab, setActiveTab } as any)
          : child
      )}
    </div>
  );
};

const TabsTrigger: React.FC<{ value: string; className?: string; children: React.ReactNode; activeTab?: string; setActiveTab?: (v: string) => void }> = ({ value, className, children, activeTab, setActiveTab }) => {
  const isActive = activeTab === value;
  return (
    <button
      onClick={() => setActiveTab?.(value)}
      className={`px-4 py-2 font-medium text-sm transition-colors ${isActive ? 'text-blue-600 border-b-2 border-blue-600' : 'text-gray-500 hover:text-gray-700'} ${className || ''}`}
    >
      {children}
    </button>
  );
};

const TabsContent: React.FC<{ value: string; className?: string; children: React.ReactNode; activeTab?: string }> = ({ value, className, children, activeTab }) => {
  if (activeTab !== value) return null;
  return <div className={className}>{children}</div>;
};
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
import { User, Heart, Settings, Upload, FileText } from 'lucide-react';
import { getCurrentUser, updateCurrentUser, uploadAvatar } from '@/services/userService';
import { getUserLikes } from '@/services/likeService';
import { getUserArticles, deleteArticle } from '@/services/articleService';
import { User as UserType } from '@/types/user';
import { Article } from '@/types/article';
import { Like } from '@/types/like';
import BlogCard from '@/components/BlogCard';
import { useRouter } from 'next/navigation';
import { ImgProcess } from '@/utils/common';

const ProfilePage: React.FC = () => {
  const router = useRouter();
  const [user, setUser] = useState<UserType | null>(null);
  const [loading, setLoading] = useState(true);
  const [likedArticles, setLikedArticles] = useState<Article[]>([]);
  const [likedArticlesLoading, setLikedArticlesLoading] = useState(false);
  const [userArticles, setUserArticles] = useState<Article[]>([]);
  const [userArticlesLoading, setUserArticlesLoading] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    bio: '',
  });
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [articleToDelete, setArticleToDelete] = useState<number | null>(null);

  // 检查用户登录状态
  useEffect(() => {
    const checkAuth = () => {
      const token = localStorage.getItem('auth_token');
      if (!token) {
        toast.error('请先登录');
        router.push('/');
        return;
      }
    };
    
    checkAuth();
  }, [router]);

  // 获取用户信息并更新到localStorage
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        setLoading(true);
        const userData: UserType = await getCurrentUser();
        
        // 将用户信息存储到localStorage
        localStorage.setItem('user', JSON.stringify(userData));
        
        setUser(userData);
        setFormData({
          username: userData.username || '',
          email: userData.email || '',
          bio: userData.bio || '',
        });
        setPreviewUrl(userData.avatar || '');
      } catch (error) {
        console.error('获取用户信息失败:', error);
        toast.error('获取用户信息失败');
      } finally {
        setLoading(false);
      }
    };

    fetchUserInfo();
  }, []);

  // 获取用户点赞的文章
  const fetchLikedArticles = async () => {
    try {
      setLikedArticlesLoading(true);
      const response = await getUserLikes({ limit: 50 });
      console.log('获取点赞文章响应:', response);
      // 将Like类型转换为Article类型（假设Like对象中包含article信息）
      const articles: Article[] = response.data.map(like => ({
        id: like.id,
        title: like?.title || '未知标题',
        content: like?.content || '',
        excerpt: like?.excerpt || '',
        author: like?.author,
        authorId: like?.author?.id || 0,
        createdAt: like?.createdAt || new Date().toISOString(),
        updatedAt: like?.updatedAt || new Date().toISOString(),
        categoryId: like?.categoryId,
        tags: like?.tags || [],
        coverImage: like?.coverImage || '',
        viewCount: like?.viewCount || 0,
        likeCount: like?.likeCount || 0,
        commentCount: like?.commentCount || 0,
        status: like?.status || 'published',
      }));
      setLikedArticles(articles);
    } catch (error) {
      console.error('获取点赞文章失败:', error);
      toast.error('获取点赞文章失败');
    } finally {
      setLikedArticlesLoading(false);
    }
  };
  
  // 当切换到点赞标签页时获取数据
  useEffect(() => {
    if (likedArticles.length === 0) {
      fetchLikedArticles();
    }
  }, []);

  // 获取用户发布的文章
  const fetchUserArticles = async () => {
    try {
      setUserArticlesLoading(true);
      const articles: Article[] = await getUserArticles();
      setUserArticles(articles);
    } catch (error) {
      console.error('获取用户文章失败:', error);
      toast.error('获取用户文章失败');
    } finally {
      setUserArticlesLoading(false);
    }
  };

  // 编辑文章
  const handleEditArticle = (articleId: number) => {
    // 跳转到编辑页面，可以复用new-article页面但需要传递articleId
    router.push(`/new-article?edit=${articleId}`);
  };

  // 打开删除确认对话框
  const handleDeleteClick = (articleId: number) => {
    setArticleToDelete(articleId);
    setDeleteDialogOpen(true);
  };

  // 确认删除文章
  const handleConfirmDelete = async () => {
    if (articleToDelete === null) return;
    
    try {
      await deleteArticle(articleToDelete);
      // 更新文章列表，设置isActive为0
      setUserArticles(prevArticles => 
        prevArticles.map(article => 
          article.id === articleToDelete ? { ...article, isActive: 0 } : article
        )
      );
      toast.success('文章删除成功');
      setDeleteDialogOpen(false);
      setArticleToDelete(null);
    } catch (error) {
      console.error('删除文章失败:', error);
      toast.error('删除文章失败');
    }
  };

  // 取消删除
  const handleCancelDelete = () => {
    setDeleteDialogOpen(false);
    setArticleToDelete(null);
  };

  // 当切换到我的文章标签页时获取数据
  useEffect(() => {
    // 这里需要监听activeTab的变化，但由于Tabs组件是自定义的，我们需要在TabsContent组件中处理
    // 或者在TabsTrigger的onClick中调用fetchUserArticles
  }, []);

  // 确保在组件加载时获取用户文章数据
  useEffect(() => {
    fetchUserArticles();
  }, []);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  // 处理头像文件选择
  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setAvatarFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreviewUrl(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  // 上传头像
  const handleUploadAvatar = async () => {
    if (!avatarFile) return;

    try {
      const formData = new FormData();
      formData.append('avatar', avatarFile);
      
      const response = await uploadAvatar(formData);
      setPreviewUrl(response.avatarUrl);
      toast.success('头像上传成功');
      setAvatarFile(null);
      
      // 更新用户信息
      const updatedUser = await getCurrentUser();
      setUser(updatedUser);
      
      // 更新localStorage中的用户信息
      localStorage.setItem('user_info', JSON.stringify(updatedUser));
    } catch (error) {
      console.error('上传头像失败:', error);
      toast.error('上传头像失败');
    }
  };

  // 保存用户信息（只保存个人简介）
  const handleSaveUserInfo = async () => {
    try {
      // 只传递bio字段进行更新
      const updatedUser = await updateCurrentUser(0,{ bio: formData.bio });
      setUser(updatedUser);
      setIsEditing(false);
      toast.success('个人简介更新成功');
      
      // 更新localStorage中的用户信息
      localStorage.setItem('user', JSON.stringify(updatedUser));
    } catch (error) {
      console.error('更新个人简介失败:', error);
      toast.error('更新个人简介失败');
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setFormData({
      username: user?.username || '',
      email: user?.email || '',
      bio: user?.bio || '',
    });
    setPreviewUrl(user?.avatar || '');
    setAvatarFile(null);
    setIsEditing(false);
  };

  if (loading) {
    return (
      <div className="container mx-auto px-4 py-8 flex justify-center items-center min-h-[80vh]">
        <div className="w-16 h-16 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin"></div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-8 text-center">个人中心</h1>
      
      <Tabs defaultValue="profile" className="max-w-3xl mx-auto">
        <TabsList className="grid grid-cols-4 mb-8">
          <TabsTrigger value="profile" className="flex items-center gap-2">
            <User className="w-4 h-4" />
            个人信息
          </TabsTrigger>
          <TabsTrigger value="liked" className="flex items-center gap-2">
            <Heart className="w-4 h-4" />
            我的点赞
          </TabsTrigger>
          <TabsTrigger value="articles" className="flex items-center gap-2">
            <FileText className="w-4 h-4" />
            我的文章
          </TabsTrigger>
          <TabsTrigger value="settings" className="flex items-center gap-2">
            <Settings className="w-4 h-4" />
            设置
          </TabsTrigger>
        </TabsList>

        {/* 个人信息标签页 */}
        <TabsContent value="profile" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>个人资料</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex flex-col items-center space-y-6">
                {/* 头像部分 */}
                <div className="relative">
                  <div className="w-32 h-32 rounded-full overflow-hidden border-4 border-white shadow-md">
                    <img 
                      src={previewUrl || `https://ui-avatars.com/api/?name=${encodeURIComponent(user?.username || 'User')}&background=random`} 
                      alt="用户头像" 
                      className="w-full h-full object-cover" 
                    />
                  </div>
                  {isEditing && (
                    <label className="absolute bottom-0 right-0 bg-blue-500 text-white rounded-full p-2 cursor-pointer hover:bg-blue-600 transition-colors">
                      <Upload className="w-5 h-5" />
                      <input 
                        type="file" 
                        accept="image/*" 
                        className="hidden" 
                        onChange={handleAvatarChange} 
                      />
                    </label>
                  )}
                </div>
                
                {isEditing && avatarFile && (
                  <Button onClick={handleUploadAvatar} className="w-full max-w-xs">
                    确认上传头像
                  </Button>
                )}

                <div className="w-full space-y-4">
                  <div className="grid grid-cols-1 gap-2">
                    <Label htmlFor="username">用户名</Label>
                    {isEditing ? (
                      <Input 
                        id="username" 
                        value={user?.username || ''} 
                        disabled 
                        readOnly 
                      />
                    ) : (
                      <div className="p-3 bg-gray-50 rounded-md">{user?.username}</div>
                    )}
                  </div>
                  
                  <div className="grid grid-cols-1 gap-2">
                    <Label htmlFor="email">邮箱</Label>
                    {isEditing ? (
                      <Input 
                        id="email" 
                        type="email" 
                        value={user?.email || ''} 
                        disabled 
                        readOnly 
                      />
                    ) : (
                      <div className="p-3 bg-gray-50 rounded-md">{user?.email}</div>
                    )}
                  </div>
                  
                  <div className="grid grid-cols-1 gap-2">
                    <Label htmlFor="bio">个人简介</Label>
                    {isEditing ? (
                      <textarea 
                        id="bio" 
                        name="bio" 
                        value={formData.bio} 
                        onChange={handleInputChange} 
                        className="w-full p-3 border border-gray-300 rounded-md min-h-[100px]" 
                      />
                    ) : (
                      <div className="p-3 bg-gray-50 rounded-md">{user?.bio || '暂无简介'}</div>
                    )}
                  </div>
                  
                  <div className="grid grid-cols-1 gap-2">
                    <Label>注册时间</Label>
                    <div className="p-3 bg-gray-50 rounded-md">
                      {user ? new Date(user.createdAt).toLocaleDateString('zh-CN') : '-'}
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
          
          {isEditing ? (
            <div className="flex justify-end gap-4">
              <Button variant="secondary" onClick={handleCancelEdit}>
                取消
              </Button>
              <Button onClick={handleSaveUserInfo}>
                保存修改
              </Button>
            </div>
          ) : (
            <div className="flex justify-end">
              <Button onClick={() => setIsEditing(true)}>
                编辑资料
              </Button>
            </div>
          )}
        </TabsContent>

        {/* 我的点赞标签页 */}
        <TabsContent value="liked">
          <Card>
            <CardHeader>
              <CardTitle>我点赞的文章</CardTitle>
            </CardHeader>
            <CardContent>
              {likedArticlesLoading ? (
                <div className="py-12 text-center">
                  <div className="w-12 h-12 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin mx-auto mb-4"></div>
                  <p>加载中...</p>
                </div>
              ) : likedArticles.length === 0 ? (
                <div className="py-12 text-center text-gray-500">
                  <p>您还没有点赞任何文章</p>
                  <Button 
                    variant="secondary" 
                    className="mt-4" 
                    onClick={() => router.push('/')}
                  >
                    去浏览文章
                  </Button>
                </div>
              ) : (
                <div className="space-y-6">
                  {likedArticles.map((article) => (
                    <BlogCard
                      key={article.id}
                      onClick={() => router.push(`/article/${article.id}`)}
                      post={{
                        id: article.id,
                        title: article.title,
                        excerpt: article.excerpt || article.content.substring(0, 150) + '...',
                        author: article.author?.username || '未知作者',
                        date: new Date(article.createdAt).toLocaleDateString('zh-CN'),
                        category: '', // 需要从categoryId获取分类名称
                        tags: (article.tags || []).map(tag => tag.name),
                        image: article.coverImage || '',
                        readTime: Math.ceil((article.content?.length || 0) / 500) + '分钟阅读',
                        viewCount: article.viewCount || 0,
                        likeCount: article.likeCount || 0
                      }} 
                    />
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 我的文章标签页 */}
        <TabsContent value="articles">
          <Card>
            <CardHeader>
              <CardTitle>我的文章</CardTitle>
            </CardHeader>
            <CardContent>
              {userArticlesLoading ? (
                <div className="py-12 text-center">
                  <div className="w-12 h-12 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin mx-auto mb-4"></div>
                  <p>加载中...</p>
                </div>
              ) : userArticles.length === 0 ? (
                <div className="py-12 text-center text-gray-500">
                  <p>您还没有发布任何文章</p>
                  <Button 
                    className="mt-4"
                    onClick={() => router.push('/new-article')}
                  >
                    去发布文章
                  </Button>
                </div>
              ) : (
                <div className="space-y-6">
                  {userArticles.map((article) => (
                    <div key={article.id} className="border rounded-lg overflow-hidden">
                      <div className="flex flex-col md:flex-row">
                        {article.coverImage && (
                          <div className="w-full md:w-1/4 h-40 md:h-auto">
                            <img 
                              src={ImgProcess(article.coverImage)} 
                              alt={article.title} 
                              className="w-full h-full object-cover" 
                            />
                          </div>
                        )}
                        <div className={`p-6 ${article.coverImage ? 'w-full md:w-3/4' : 'w-full'}`}>
                          <div className="flex justify-between items-start mb-2">
                            <h3 className="text-xl font-semibold">{article.title}</h3>
                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                              article.isActive === 1 ? 'bg-green-100 text-green-800' : 
                              article.isActive === -1 ? 'bg-yellow-100 text-yellow-800' : 
                              'bg-gray-100 text-gray-800'
                            }`}>
                              {article.isActive === 1 ? '已通过' : 
                               article.isActive === -1 ? '未审核' : 
                               '已删除'}
                            </span>
                          </div>
                          
                          <div className="text-sm text-gray-600 mb-4">
                            <span className="mr-4">分类: {article.category?.name || '未分类'}</span>
                            <span>
                              标签: {article.tags?.map(tag => tag.name).join(', ') || '无标签'}
                            </span>
                          </div>
                          
                          <p className="text-gray-700 mb-4 line-clamp-2">
                            {article.excerpt || article.content.substring(0, 150) + '...'}
                          </p>
                          
                          <div className="flex justify-between items-center">
                            <span className="text-sm text-gray-500">
                              创建时间: {new Date(article.createdAt).toLocaleDateString('zh-CN')}
                            </span>
                            <div className="flex gap-2">
                              <Button 
                                variant="secondary" 
                                size="sm"
                                onClick={() => handleEditArticle(article.id)}
                              >
                                编辑
                              </Button>
                              <Button 
                                variant="destructive" 
                                size="sm"
                                onClick={() => handleDeleteClick(article.id)}
                              >
                                删除
                              </Button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 设置标签页 */}
        <TabsContent value="settings">
          <Card>
            <CardHeader>
              <CardTitle>账号设置</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div className="flex items-center justify-between p-4 border rounded-md">
                  <span className="text-gray-700">修改密码（后续完善 邮箱验证 及当前密码验证后即可重新修改密码 ）</span>
                  <Button variant="secondary">
                    前往修改
                  </Button>
                </div>
                
                <div className="flex items-center justify-between p-4 border rounded-md">
                  <span className="text-gray-700">通知设置（后续完善 可设置 邮箱接收什么类型的文章提醒）</span>
                  <Button variant="secondary">
                    前往设置
                  </Button>
                </div>
                
                <Separator />
                
                <div className="p-4 border border-red-200 rounded-md bg-red-50">
                  <h4 className="text-lg font-medium text-red-700 mb-2">注销账号</h4>
                  <p className="text-red-600 mb-4">
                    注销账号后，您的所有数据将被永久删除，此操作不可恢复。
                  </p>
                  <Button variant="destructive" className="w-full">
                    注销账号（后续完善 需邮箱验证后即可注销账号）
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
      
      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这篇文章吗？此操作不可恢复。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="secondary" onClick={handleCancelDelete}>
              取消
            </Button>
            <Button variant="destructive" onClick={handleConfirmDelete}>
              确认删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default ProfilePage;
